package com.java.framework.utils.page;

import java.text.MessageFormat;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

public class Pager<T> extends PageRequest {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public final static int MAX_PAGE_SIZE=200;
	public final static int DEFAULT_PAGE_SIZE=10;
	public final static int DEFAULT_CURRENT_PAGE=0;
	
	private final static String CURRENT_PAGE_TEXT = "&nbsp;当前第{0}页,";//当前第{0}页
	private final static String PER_PAGE_ITEM_TEXT = "每页显示{0}条,";//每页显示{0}条
	private final static String TOTAL_PAGE_ITEM_TEXT = "共{0}条";//共{0}条
	private final static String TOTAL_PAGE_TEXT = "共{0}页";//共{0}条
	private final static String PER_PAGE_MAX_ITEM_TEXT = "每页最多显示" + MAX_PAGE_SIZE + "条" ;//每页最多显示{0}条
	
	private int currentPage = DEFAULT_CURRENT_PAGE;
	private int pageSize = DEFAULT_PAGE_SIZE;
	private Sort sort;
	private long totalObjects;
	private int totalPages;
	private List<T> pageList;
	
	private String funcName = "page"; // 设置点击页码调用的js函数名称，默认为page，在一页有多个分页对象时使用。
	private int length = 8;// 显示页面长度
	private int slider = 1;// 前后显示页面长度
	
	private int first;// 首页索引
	private int last;// 尾页索引
	private int prev;// 上一页索引
	private int next;// 下一页索引
	
	public Pager(int currentPage, int pageSize) {
		this(currentPage, pageSize, null);
	}
	
	/**
	 * @param currentPage
	 *            当前页(从0开始)
	 * @param pageSize
	 *            页面大小
	 * @param sort
	 * 			排序           
	 */
	public Pager(int currentPage, int pageSize, Sort sort) {
		super(currentPage, pageSize, sort);
		
		if (pageSize < 1){
			pageSize = DEFAULT_PAGE_SIZE ;
		}else if(pageSize>MAX_PAGE_SIZE){
			pageSize = MAX_PAGE_SIZE ;
		}
		if (currentPage < 0){
			currentPage = DEFAULT_CURRENT_PAGE ;
		}
		this.currentPage = currentPage;
		this.pageSize = pageSize;
		this.sort = sort;
	}
	
	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public Sort getSort() {
		return sort;
	}

	public void setSort(Sort sort) {
		this.sort = sort;
	}

	public long getTotalObjects() {
		return totalObjects;
	}

	public void setTotalObjects(long totalObjects) {
		this.totalObjects = totalObjects;
	}

	public List<T> getPageList() {
		return pageList;
	}

	public void setPageList(List<T> pageList) {
		this.pageList = pageList;
	}

	public void initialize() {
		// 1
		this.first = DEFAULT_CURRENT_PAGE;

		this.last = (int)(totalObjects / this.pageSize + first - 1) ;
		
		this.totalPages = (int)(totalObjects % pageSize == 0 ? totalObjects / pageSize : totalObjects / pageSize + 1);

		if (this.totalObjects % this.pageSize != 0 || this.last < 0) {
			this.last++;
		}

		if (this.last < this.first) {
			this.last = this.first;
		}

		if (this.currentPage < 0) {
			this.currentPage = this.first;
		}

		if (this.currentPage > this.last) {
			this.currentPage = this.last;
		}

		if (this.currentPage < this.last - 1) {
			this.next = this.currentPage + 1;
		} else {
			this.next = this.last;
		}

		if (this.currentPage > 1) {
			this.prev = this.currentPage - 1;
		} else {
			this.prev = this.first;
		}

		// 2
		if (this.currentPage < this.first) {// 如果当前页小于首页
			this.currentPage = this.first;
		}

		if (this.currentPage > this.last) {// 如果当前页大于尾页
			this.currentPage = this.last;
		}
	}

	public String getPageText(){
		initialize();

		StringBuilder sb = new StringBuilder();
		StringBuilder tmp = new StringBuilder();
		
		if (currentPage == first) {// 如果是首页
			sb.append("<li class=\"disabled\"><a href=\"javascript:\">&#171;&#171;</a></li>\n");
		} else {
			sb.append("<li><a href=\"javascript:\" onclick=\""
					+ funcName + "(" + prev + "," + pageSize + ");\">&#171;&#171;</a></li>\n");
		}

		int begin = currentPage - (length / 2);

		if (begin < first) {
			begin = first;
		}

		int end = begin + length - 1;

		if (end > last) {
			end = last;
			begin = end - length + 1;
			if (begin < first) {
				begin = first;
			}
		}

		if (begin > first) {
			int i = 0;
			for (i = first; i < first + slider && i < begin; i++) {
				sb.append("<li><a href=\"javascript:\" onclick=\""
						+ funcName + "(" + i + "," + pageSize + ");\">"
						+ (i + 1 - first) + "</a></li>\n");
			}
			if (i < begin) {
				sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n");
			}
		}

		for (int i = begin; i <= end; i++) {
			if (i == currentPage) {
				sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first) + "</a></li>\n");
			} else {
				sb.append("<li><a href=\"javascript:\" onclick=\""
						+ funcName + "(" + i + "," + pageSize + ");\">" + (i + 1 - first) + "</a></li>\n");
			}
		}

		if (last - end > slider) {
			sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n");
			end = last - slider;
		}

		for (int i = end + 1; i <= last; i++) {
			sb.append("<li><a href=\"javascript:\" onclick=\""
					+ funcName + "(" + i + "," + pageSize + ");\">" + (i + 1 - first) + "</a></li>\n");
		}

		if (currentPage == last) {
			sb.append("<li class=\"disabled\"><a href=\"javascript:\"> &#187;&#187;</a></li>\n");
		} else {
			sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "("
					+ next + "," + pageSize + ");\">" + " &#187; &#187;</a></li>\n");
		}

		sb.append("<li class=\"disabled controls\"> \n");
		
		MessageFormat formatter = new MessageFormat(TOTAL_PAGE_TEXT);
		String msg = formatter.format(new Object[]{totalPages});

		//当前第{0}页
		tmp.setLength(0);
		tmp.append("<input type=\"text\"style=\"width: 50px;\" class=\"form-control\" oldValue=\"" + currentPage + "\" value=\"" + (currentPage+1)
				+ "\" onkeypress=\"var reg=/^[0-9]*$/; var e=e?e:event; var c=e.keyCode||e.which;"
				+ "if(c==13 && (!reg.test(this.value) || parseFloat(this.value)<0 )) this.value=$(this).attr('oldValue');"
				+ "else if( c==13 && (!reg.test($(this).val()) || parseFloat($(this).val())>"
				+ totalPages + ") ){alert('" + msg + "');$(this).val('"+ totalPages + "');}"
				+ "else if(c==13)");
		tmp.append(funcName + "(this.value-1,$(this).next().val());\" onclick=\"this.select();\"/> ");

		formatter = new MessageFormat(CURRENT_PAGE_TEXT);
		msg = formatter.format(new Object[]{tmp.toString(),totalPages});
		sb.append(" ").append( msg );

		//每页显示{0}条
		tmp.setLength(0);
		tmp.append("<input type=\"text\" style=\"width: 50px;\" class=\"form-control\" oldValue=\"" + pageSize + "\" value=\"" + pageSize
				+ "\" onkeypress=\"var reg=/^[0-9]*$/; var e=e?e:event; var c=e.keyCode||e.which;"
				+ "if(c==13 && (!reg.test(this.value) || parseFloat(this.value)<=0 )) this.value=$(this).attr('oldValue');"
				+ "else if(c==13 && (!reg.test(this.value) || parseFloat(this.value)>"
				+ MAX_PAGE_SIZE + ") ){alert('" + PER_PAGE_MAX_ITEM_TEXT + "');this.value='"
				+ MAX_PAGE_SIZE + "';}"
				+ "else if(c==13)");
		tmp.append(funcName + "("+ DEFAULT_CURRENT_PAGE +",this.value);\" onclick=\"this.select();\"/> ");

		formatter = new MessageFormat(PER_PAGE_ITEM_TEXT);
		msg = formatter.format(new Object[]{tmp.toString()});
		sb.append(" ").append(  msg );

		//共{0}条
		formatter = new MessageFormat(TOTAL_PAGE_ITEM_TEXT);
		msg = formatter.format(new Object[]{ totalObjects });
		sb.append(" ").append(  msg );

		sb.append("<li>\n");

		sb.insert(0, "<div class=\"form-inline\"><ul class=\"pagination\">\n").append("</ul></div>\n");

		return sb.toString();
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return getPageText();
	}
}
